<?php

namespace App\Console\Commands\Clickhouse;

use App\Models\Common\ConfigModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OptimizeTableFinal extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clickhouse:optimize-table-final';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '优化表格索引';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $config = ConfigModel::getValueNewJson('clickHouse', 'optimizeTableFinal');

        if (empty($config)) {
            return;
        }

        // 组建需要执行的SQL
        foreach ($config as $connect => $tables) {
            foreach ($tables as $table) {

                // 执行SQL
                execTime(function () use ($connect, $table){
                    DB::connection($connect)->statement("OPTIMIZE table {$table} final;");
                }, $table);

                // 添加日志
                Log::info("ClickHouse优化表格索引-连接配置：{$connect} 数据表：{$table}");
            }
        }
    }
}
